#include<iostream>
#include "Log.hpp"
#include "UdpServer.hpp"
#include <string>
#include "Common.hpp"
#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace LogModule;
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " localport" << std::endl;
        Die(USAGE_ERR);
    }
    ENABLE_CONSOLE_LOG();
    // ip + port
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    int sockfd = socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        Die(SOCKET_ERR);
    }
    struct sockaddr_in tmp;
    memset(&tmp, 0, sizeof(tmp));
    tmp.sin_family = AF_INET;
    tmp.sin_port=::htons(serverport);
    tmp.sin_addr.s_addr = inet_addr(serverip.c_str());

    while(true)
    {
        std::cout<<"输入你要说的话"<<std::endl;
        std::string tstring;
        std::getline(std::cin,tstring);

        int n = ::sendto(sockfd,tstring.c_str(),tstring.size(),0,CONV(&tmp),sizeof(tmp));
        if(n<0)
        {
            LOG(LogLevel::FATAL)<<"Client send to false";
        }

        char inbuffer[1024];
        struct sockaddr_in server;
        socklen_t len = sizeof(server);
        int m = ::recvfrom(sockfd,inbuffer,sizeof(inbuffer)-1,0,CONV(&server),&len);
        if(m>0)
        {
            inbuffer[m] = 0;
            std::cout<<inbuffer<<std::endl;
        }

    }
  

    return 0;
}



